package com.xiaozheng.dao.impl;

import com.xiaozheng.dao.AccountDao;
import com.xiaozheng.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.List;

/**
 * @Package: com.xiaozheng.dao.impl
 * @ClassName: AccountDaoImpl
 * @Author: 小政同学    QQ:xiaozheng666888@qq.com
 * @CreateTime: 2020/9/25 12:46
 * @What_is_this_file_for: 账户持久层实现类
 * @Description: 描述
 */
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

    /**
     * 查询所有
     *
     * @return
     */
    @Override
    public List<Account> findAllAcount() {
        // conn-要在其中执行查询的连接。sql-要执行的查询。 rsh-将结果转换为对象的处理程序。返回：处理程序返回的对象。
        return super.getJdbcTemplate().query("select * from account", new BeanPropertyRowMapper<>(Account.class));
    }

    /**
     * 根据id查询一个
     *
     * @return
     */
    @Override
    public Account findAccountById(Integer AccountId) {
        Account account = null;
        account = super.getJdbcTemplate().queryForObject("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), AccountId);
        return account;
    }

    /**
     * 保存
     *
     * @param account
     */
    @Override
    public void saveAccount(Account account) {
        super.getJdbcTemplate().update("insert into account(uid,money)values(?,?)", account.getUid(), account.getMoney());
    }

    /**
     * 更新
     *
     * @param account
     */
    @Override
    public void updateAccount(Account account) {
        super.getJdbcTemplate().update("update account set uid = ?,money = ? where id = ?", account.getUid(), account.getMoney(),account.getId());
    }

    /**
     * 根据id删除
     *
     * @param AccountId
     */
    @Override
    public void deleteAccount(Integer AccountId) {
        super.getJdbcTemplate().update("delete from account where id = ?", AccountId);
    }

    /**
     * 根据Uid查询账户
     *
     * @param accountUid
     * @return 如果有唯一的结果就返回，如果没有结果就返回null
     * 如果结果集超过一个就抛出异常
     */
    @Override
    public Account findByUId(String accountUid) {
        List<Account> accounts = null;
        //获得结果集
        accounts = super.getJdbcTemplate().query("select * from account where uid = ?", new BeanPropertyRowMapper<>(Account.class), accountUid);
        //如果有唯一的结果就返回，如果没有结果就返回null
        if (accounts == null || accounts.size() == 0) {
            return null;
        }
        //如果结果集超过一个就抛出异常
        if (accounts.size() > 1) {
            throw new RuntimeException("结果集不唯一，数据有问题");
        }

        // return accounts;
        //断言
        assert accounts != null;
        //返回在此列表中指定位置的元素。
        return accounts.get(0);
    }

}
